<template>
  <div class="table-box">
    <ProTable ref="proTable" title="物料列表" :columns="columns" :data="selfMadeList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <SelectFilter :data="filterData" @change="changeFilter" :default-values="filterResult" />
        <el-button type="primary" :icon="CirclePlus" @click="openDrawerStatic('新增')">新增自制物料</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="Setting" @click="toDetail_structure(scope.row)">物料结构</el-button>
        <el-button type="primary" link :icon="EditPen" @click="toDetail(scope.row)">工序流程</el-button>
        <el-button type="primary" link :icon="View" @click="openDrawerStatic('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawerStatic('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <MaterialS ref="drawerRef" @refresh="refreshTable" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, onMounted } from "vue";
import { Material } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Setting } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import MaterialS from "@/views/proTable/components/MaterialS.vue";
import SelectFilter from "@/components/SelectFilter/index.vue";
import { materialType } from "@/utils/serviceDict";
import { useRouter, useRoute } from "vue-router";
import { useTabsStore } from "@/stores/modules/tabs";
import axios from "axios";

const router = useRouter();
const route = useRoute();
const tabStore = useTabsStore();
const filterResult = ref({ state: "1" });
const selfMadeList = ref<Partial<Material.ResMaterial>[]>([]);
const baseUrl = import.meta.env.VITE_BASE_URL;

console.log("baseUrl = ", baseUrl);

// 在组件挂载时初始化数据
onMounted(() => {
  initFormData();
});

const initFormData = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    console.log("userId = ", userId);
    //数据库
    const response = await axios.post(baseUrl + "/api/carbon/getAllMaterials?sourceType=1", {
      userId: userId
    });
    console.log("响应数据_读取外购材料列表:", response.data);
    if (response.data && response.data.code === 200) {
      selfMadeList.value = response.data.data;
      selfMadeList.value = response.data.data.map((item: any) => ({
        ...item,
        materialType: String(item.materialType)
      }));
      console.log("自制材料列表:", selfMadeList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取自制材料列表失败";
      console.error("获取自制材料列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取自制材料列表出错:", error);
    ElMessage.error("获取自制材料列表失败，可能是因为参数错误或网络问题");
  }
};

const changeFilter = (val: typeof filterResult.value) => {
  filterResult.value = val;
  if (val.state === "2") {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push({
      path: "/basicData/productConfig/material/indexP"
    });
  }
};
const toDetail = (row: any) => {
  router.push({
    path: `/basicData/productConfig/material/detail/${row.id}`
  });
};

const filterData = [
  {
    title: "物料来源",
    key: "state",
    options: [
      {
        label: "自制物料",
        value: "1",
        icon: "Guide"
      },
      {
        label: "外购物料",
        value: "2",
        icon: "Van"
      }
    ]
  }
];

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps<Material.ResMaterial>[] = [
  { type: "selection", fixed: "left", width: 80 }, // 多选列
  {
    prop: "id",
    label: "物料编号",
    search: { el: "input" } // 搜索框
  },
  {
    prop: "materialName",
    label: "物料名称",
    search: { el: "input" } // 搜索框
  },
  {
    prop: "materialType",
    label: "物料类型",
    width: 200,
    enum: materialType, // 使用字典映射物料类型
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: 180,
    search: {
      el: "date-picker", // 日期选择器
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }, // 配置为时间区间
      defaultValue: ["2023-01-01 00:00:00", "2023-12-31 23:59:59"]
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 500 } // 操作列
];

//删除静态数组
const deleteAccount = async (params: Material.ResMaterial) => {
  ElMessageBox.confirm("是否删除该项?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning", // 使用字符串形式的类型
    draggable: true
  })
    .then(async () => {
      try {
        const response = await axios.post(baseUrl + "/api/carbon/deleteMaterial", {
          id: params.id
        });
        if (response.data && response.data.code === 200) {
          ElMessage({
            type: "success",
            message: "删除材料成功!"
          });
          await initFormData(); // 删除成功后刷新列表
        } else {
          ElMessage.error(response.data.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除材料出错:", error);
        ElMessage.error("删除材料失败，可能是因为参数错误或网络问题");
      }
    })
    .catch(() => {
      // 如果用户取消了操作，则不做任何处理
    });
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof MaterialS> | null>(null);

// 静态方法（操作静态数组）
const openDrawerStatic = (title: string, row: Partial<Material.ResMaterial> = {}) => {
  // 定义静态操作
  const params = {
    title,
    isView: title === "查看",
    row: { ...row } // 静态模式下仅操作此行数据
  };
  drawerRef.value?.acceptParams(params);
};

const toDetail_structure = (row: any) => {
  ElMessage.error("功能尚未开放，请直接定义对应产品的数据结构！");
  console.log("row = ", row);
  // router.push({
  //   path: `/basicData/productConfig/material/detail_structure/${row.id}`
  // });
};

// 添加刷新方法
const refreshTable = async () => {
  await initFormData();
};
</script>
